﻿using Direct.IDAL.User.Jurisdiction;
using DirectSell.Common.CodeHelp;
using DirectSell.Common.Session;
using DirectSell.IBLL;
using DirectSell.Model.User;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace DirectSell.WebLayer.Controllers
{
    public class UserLoginController : Controller
    {
        #region 依赖注入--郭文昊--2018年10月28日21:18:13
        /// <summary>
        /// 用户登录
        /// </summary>
        [Dependency("UserLogin")]
        protected IOperation _login { get; set; }
        [Dependency]
        protected ILoginRepository _repository { get; set; }

        #endregion

        #region 用户登录页--郭文昊--2018年10月28日21:26:58
        /// <summary>
        /// 用户登录页
        /// </summary>
        /// <returns></returns>
        // GET: UserLogin
        public ActionResult Index(string usercode =null)
        {
            if (usercode != null)
            {
                //usercode = DirectSell.Common.DES.Des1.Decrypt(usercode);
                var userinfo = _repository.GetUserInfo(usercode);
                //存session
                SessionModel session = new SessionModel()
                {
                    UserId = userinfo.UserId,
                    UserCode = userinfo.UserCode,
                    RefereeCode = userinfo.RefereeCode,
                    ServiceCentreCode = userinfo.ServiceCentreCode,
                    UserName = userinfo.UserName,
                    UserLevel = userinfo.UserLevel
                };
                SessionInfo.SetSession(session);
                return Redirect("/User/Home/Index");
            }

            return View();
        }
        #endregion

        #region 用户登录操作--郭文昊--2018年10月28日21:27:13
        /// <summary>
        /// 用户登录操作
        /// </summary>
        /// <param name="info">用户登录信息</param>
        /// <returns></returns>
        public async Task<UserRespCode> Login(UserLoginInfo info)
        {
            //判断验证码是否正确
            if (SessionHelper.GetSession("CheckCode") == null || info.checkCode !=SessionHelper.GetSession("CheckCode").ToString())
            {
                //验证码错误
                return UserRespCode.验证码错误;
            }

            return await _login.DoOperationAsync(info);
        }
        #endregion

        #region 获取图片验证码--郭文昊--2018年10月28日23:36:26
        /// <summary>
        /// 获取图片验证码 
        /// </summary>
        /// <returns></returns>
        public ActionResult GetImageValiDateCode()
        {
            //获得验证码
            string code = ValidateCode.GetRandNumber(4);
            byte[] bytes = ValidateCode.CreateCheckCode(code);
            //验证码写入Session
            SessionHelper.SetSession("CheckCode", code);
            return File(bytes, @"image/jpeg");
        }
        #endregion

    }
}